package org.elanfox.cloud.utils;


/**
 * 地图相关
 *
 * @author allan
 * @date 05/12/2017
 */
public class MapUtils {
    /**
     * 地球半径
     * 单位：千米
     */
    private static final double EARTH_RADIUS = 6371;

    /**
     * 将角度换算为弧度
     *
     * @param degrees
     * @return
     */
    public static double convertDegreesToRadians(double degrees) {
        return degrees * Math.PI / 180;
    }

    /**
     * 将弧度换算为角度
     *
     * @param radian
     * @return
     */
    public static double convertRadiansToDegrees(double radian) {
        return radian * 180.0 / Math.PI;
    }

    public static double haverSin(double theta) {
        double v = Math.sin(theta / 2);
        return v * v;
    }

    /**
     * 给定的经度1，纬度1；经度2，纬度2. 计算2个经纬度之间的距离。
     *
     * @param lat1
     * @param lon1
     * @param lat2
     * @param lon2
     * @return 返回两个经纬度之间的距离，单位m
     */
    public static double distance(double lat1, double lon1, double lat2, double lon2) {
        //用haversine公式计算球面两点间的距离。
        //经纬度转换成弧度
        lat1 = convertDegreesToRadians(lat1);
        lon1 = convertDegreesToRadians(lon1);
        lat2 = convertDegreesToRadians(lat2);
        lon2 = convertDegreesToRadians(lon2);

        //差值
        double vLon = Math.abs(lon1 - lon2);
        double vLat = Math.abs(lat1 - lat2);

        //h is the great circle distance in radians, great circle就是一个球体上的切面，它的圆心即是球心的一个周长最大的圆。
        double h = haverSin(vLat) + Math.cos(lat1) * Math.cos(lat2) * haverSin(vLon);

        double distance = 2 * EARTH_RADIUS * Math.asin(Math.sqrt(h));

        return distance * 1000;
    }
}
